<script setup lang="ts">
import { ref } from "vue";
import { Modal, Upload, Button, Alert, message } from "ant-design-vue";
import { UploadOutlined, DownloadOutlined } from "@ant-design/icons-vue";
import type { School } from "../types/school";
import { parseExcel, downloadTemplate } from "../utils/excelImport";
import { UploadChangeParam } from "ant-design-vue/es/upload";
import Api from "@/api/school.js";

const props = defineProps<{
  visible: boolean;
}>();

const emit = defineEmits(["close", "import"]);

// 上传的文件列表
const fileList = ref<any[]>([]);

// 解析出的学校数据
const parsedSchools = ref<School[]>([]);

// 是否有错误数据
const hasErrors = ref(false);

// 加载状态
const loading = ref(false);

// 上传接口
const customRequest = ({ file, onSuccess }: any) => {
  // 模拟上传成功
  setTimeout(() => {
    onSuccess("ok");
  }, 0);
};

// 处理文件上传变化
const handleChange = async (info: UploadChangeParam) => {
  fileList.value = info.fileList.slice(-1); // 只保留最后一个文件

  // 当文件上传完成时开始解析
  if (info.file.status === "done") {
    const file = info.file.originFileObj;
    if (!file) return;

    loading.value = true;
    try {
      const result = await parseExcel(file);
      parsedSchools.value = result.schools;
      hasErrors.value = result.hasErrors;

      if (result.hasErrors) {
        message.warning("部分学校信息不完整，请查看标记");
      } else {
        message.success("文件解析成功");
      }
    } catch (error) {
      message.error("文件解析失败，请检查文件格式");
      console.error(error);
    } finally {
      loading.value = false;
    }
  }
};

// 校验文件类型
const beforeUpload = (file: File) => {
  const isExcel =
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel" ||
    file.name.endsWith(".xlsx") ||
    file.name.endsWith(".xls") ||
    file.name.endsWith(".csv");

  if (!isExcel) {
    message.error("您只能上传Excel文件!");
  }

  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error("文件必须小于10MB!");
  }

  return isExcel && isLt10M;
};

// 确认导入
const confirmImport = async () => {
  if (parsedSchools.value.length === 0) {
    message.error("请先上传并解析Excel文件");
    return;
  }

  loading.value = true;
  try {
    // const formData = new FormData();
    // formData.append("file", fileList.value[0].originFileObj);
    await Api.importFile(
      { file: fileList.value[0].originFileObj },
      localStorage.getItem("dsCode")
    );
    message.success("导入成功");
    emit("close");
    emit("import");
  } catch (error) {
    message.error("导入失败");
  } finally {
    loading.value = false;
  }
};

// 取消导入
const handleCancel = () => {
  resetForm();
  emit("close");
};

// 重置表单
const resetForm = () => {
  fileList.value = [];
  parsedSchools.value = [];
  hasErrors.value = false;
};

// 下载模板
const handleDownloadTemplate = (e: Event) => {
  e.stopPropagation(); // 阻止事件冒泡
  downloadTemplate();
};
</script>

<template>
  <Modal
    :open="visible"
    title="导入学校信息"
    @cancel="handleCancel"
    :maskClosable="false"
    width="600px"
  >
    <div v-if="hasErrors" class="import-warning">
      <Alert
        message="部分学校信息不完整"
        description="Excel中有部分学校信息不完整，导入后将被标记。您可以在导入后补充这些信息。"
        type="warning"
        show-icon
      />
    </div>

    <div class="upload-container">
      <Upload
        name="file"
        :file-list="fileList"
        :custom-request="customRequest"
        :before-upload="beforeUpload"
        @change="handleChange"
        :maxCount="1"
      >
        <Button :loading="loading" :disabled="fileList.length >= 1">
          <upload-outlined /> 选择Excel文件
        </Button>
        <Button
          type="link"
          @click="handleDownloadTemplate"
          class="download-template-btn"
        >
          <download-outlined /> 下载导入模板
        </Button>
      </Upload>

      <div class="file-info" v-if="parsedSchools.length > 0">
        <p>已解析 {{ parsedSchools.length }} 条学校记录</p>
      </div>
    </div>

    <template #footer>
      <Button @click="handleCancel">取消</Button>
      <Button
        type="primary"
        @click="confirmImport"
        :loading="loading"
        :disabled="parsedSchools.length === 0"
      >
        确认导入
      </Button>
    </template>
  </Modal>
</template>

<style scoped>
.upload-container {
  margin: 24px 0;
}

.import-warning {
  margin-bottom: 24px;
}

.file-info {
  margin-top: 16px;
  color: #666;
}

.download-template-btn {
  margin-left: 16px;
}
</style>
